package com.ifonly.mvc;

import com.ifonly.config.Configuration;
import com.ifonly.handler.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-16 09:08
 * @since JDK 1.6
 */
public class ActionViewHandler extends Handler {
    ActionMapper actionMapper = ActionMapper.getInstance();

    @Override
    public void handle(String target,
                       HttpServletRequest request,
                       HttpServletResponse response,
                       boolean[] isHandled) {

        if (Configuration.getInstance().isDevMode() &&
                target.equals(Configuration.getInstance().getActionViewUrl())) {
            Set<String> allMappingUrl = actionMapper.allMappingUrl();

            PrintWriter out = null;

            try {
                out = response.getWriter();

                StringBuilder sb = new StringBuilder();
                sb.append("<html>")
                    .append("<head>")
                    .append("<title>")
                    .append("Action View")
                    .append("</title>")
                    .append("</head>")
                    .append("<body>");

                for (String url : allMappingUrl) {
                    sb.append(url).append("<br/>");
                }

                sb.append("</body>")
                    .append("</html>");

                out.write(sb.toString());
                out.flush();

                isHandled[0] = true;
                return;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }


        }
        next.handle(target, request, response, isHandled);
    }

}
